/* Copyright (c) 2001, Nokia Mobile Phones. All rights reserved */

#include <eikenv.h>
#include <msvids.h>
#include <mtclreg.h>
#include <mtclbase.h>
#include <txtrich.h>
#include <smsclnt.h>
#include <smuthdr.h>
#include <smutset.h>
#include "MsvHandler.h"


CMsvHandler::CMsvHandler(MMsvObserver& aObserver)
    : CActive(EPriorityStandard), iOperation(NULL), iSession(NULL), iMtm(NULL), 
      iMtmRegistry(NULL), iObserver(aObserver)
    {
    CActiveScheduler::Add(this);
    }


TBool CMsvHandler::IsIdle()
    {
    // The session must have been established to have created an MtmRegistry
    return (iMtmRegistry ? ETrue : EFalse);
    }

CMsvHandler::~CMsvHandler()
    {
    Cancel(); // Causes call to DoCancel() if active

    delete iOperation;
    iOperation = NULL;

    delete iMtm;
    iMtm = NULL;

    delete iMtmRegistry;
    iMtmRegistry = NULL;

    delete iSession;    // session must be deleted last (and constructed first)
    iSession = NULL;
    }


void CMsvHandler::ConstructL()
    {
    // Create CMsvSession. The server reports completion via the
    // MMsvSessionObserver::HandleSessionEventL. Clients may use the session only when
    // this event has been consumed.
    iSession = CMsvSession::OpenAsyncL(*this);
    }


void CMsvHandler::CompleteConstructL()
    {
    // We get a MtmClientRegistry from our session
    // this registry is used to instantiate new mtms.
    iMtmRegistry = CClientMtmRegistry::NewL(*iSession);
    }


void CMsvHandler::DoCancel()
    {
    // Cancel any outstanding operations
    if (iOperation)
        {
        iOperation->Cancel();
        }
    }

void CMsvHandler::SetMtmEntryL(TMsvId aEntryId)
    {
    // Get the server entry from our session
    CMsvEntry* entry = iSession->GetEntryL(aEntryId);
    CleanupStack::PushL(entry);
    
    // Check if our mtm is different from the mtm set to our entry
    if ((iMtm == NULL) || (entry->Entry().iMtm != (iMtm->Entry()).Entry().iMtm))
        {
        // If so, we delete the old... 
        delete iMtm;
        iMtm = NULL;
        
        // ...and get a new one from the MtmRegistry
        iMtm = iMtmRegistry->NewMtmL(entry->Entry().iMtm);
        }

    iMtm->SetCurrentEntryL(entry);
    CleanupStack::Pop(entry); 
    }

void CMsvHandler::DeleteEntryL(TMsvEntry& aMsvEntry)
    {
    // Take a handle to the parent entry
    CMsvEntry* parentEntry = CMsvEntry::NewL(*iSession, aMsvEntry.Parent(), TMsvSelectionOrdering());

    CleanupStack::PushL(parentEntry);

    // here parentEntry is the Sent folder (must be so that we can call DeleteL) 
    iOperation = parentEntry->DeleteL(aMsvEntry.Id(), iStatus);

    CleanupStack::PopAndDestroy(parentEntry);

    SetActive();
    }

